package com.xue;

import java.io.File;
import java.util.Optional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.CacheManager;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.xue.common.util.SpringContext;
import com.xue.pojo.sys.SysUser;
import com.xue.service.sys.ICodeTranslator;

/**
 * Description: 系统常量和常用方法 <br/>
 * Date: 2018-07-22 上午8:45:38 <br/>
 * 
 * @author xuejianxinokok@163.com
 */
public class AppContext {
	private static final Logger logger = LoggerFactory.getLogger(AppContext.class);
	private static final String KEY_CURRENT_USER = "bwiev3.user";
	public static final String SYSTEM_TMPDIR = System.getProperty("java.io.tmpdir") + File.separator;
	public static final String VALIDATE_CODE = "validateCode";
	// 系统魔数 用于token验证
	public static final String SYSTEM_MAGIC = "bwietoken20190328xfakjhfdakljbbkajdhfajd";

	public static final String SYS_CODE = "syscode";

	//private static final ThreadLocal<WeakReference<HttpSession>> userSession = new ThreadLocal<WeakReference<HttpSession>>();

	//public static final void setSession(HttpSession session) {
		// 保存当前session
	//	userSession.set(new WeakReference<HttpSession>(session));
	//}

	//public static final void removeSession() {
		// 移除当前session
	//	userSession.remove();
	//}

	//@SuppressWarnings("unchecked")
	//public static <T extends SysUser> T getLoginUser() {
	//	return (T) Optional.ofNullable(userSession.get()).map(o -> o.get()).map(s -> s.getAttribute(KEY_CURRENT_USER))
	//			.orElseThrow(() -> new AppException("用户信息失效,请重新登陆!"));
	//}

	public static <T extends SysUser> void setLoginUser( T user) {
		setSessionAttribute(KEY_CURRENT_USER, user);
	}

	@SuppressWarnings("unchecked")
	public static <T extends SysUser> T getLoginUser() {
		return (T) getSessionAttribute(KEY_CURRENT_USER);
	}

	public static void logout() {
		getSession().invalidate();
	}
	
	private static CacheManager cm;// 缓存管理器
	private static ICodeTranslator codeTranslator;// 代码翻译器
	public static final String CACHE_DEFAULT = "default";
	public static final String CACHE_10_MINUTE = "minute10";
	public static final String CACHE_1_HOUR = "hours1";
	public static final String CACHE_1_DAY = "day1";

	/**
	 * 
	 * Description: 从缓存中获取值 <br/>
	 * Date:2019年4月3日 上午11:26:11
	 * 
	 * @author xuejianxin
	 * @param cacheName
	 * @param key
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <V> Optional<V> getCacheValue(String cacheName, String key) {
		if (null == cm) {
			logger.info("init CacheManager");
			cm = SpringContext.get().getBean(CacheManager.class);
		}
		return Optional.ofNullable(cm.getCache(cacheName)).map(c -> c.get(key)).map(rv -> (V) rv.get());
	}

	public static <V> Optional<V> getCacheValue(String key) {
		return getCacheValue(CACHE_DEFAULT, key);
	}

	/**
	 * 
	 * Description: 保存到缓存 <br/>
	 * Date:2019年4月3日 上午11:41:44
	 * 
	 * @author xuejianxin
	 * @param cacheName 缓存名称
	 * @param key       缓存key
	 * @param value     缓存值
	 */
	public <V> void setCacheValue(String cacheName, String key, V value) {
		if (null == cm) {
			cm = SpringContext.get().getBean(CacheManager.class);
		}
		Optional.ofNullable(cm.getCache(cacheName)).orElseThrow(() -> new RuntimeException(cacheName + "不存在!")).put(key,
				value);
	}

	/**
	 * 
	 * Description: 保存值到缓存默认永远缓存 <br/>
	 * Date:2019年4月3日 上午11:42:42
	 * 
	 * @author xuejianxin
	 * @param key
	 * @param value
	 */
	public <V> void setCacheValue(String key, V value) {
		setCacheValue(CACHE_DEFAULT, key, value);
	}

	/**
	 * 
	 * Description: 翻译代码到名称 <br/>
	 * Date:2019年4月4日 下午2:54:50
	 * 
	 * @author xuejianxin
	 * @param codeType 代码类型
	 * @param code     要翻译的代码
	 * @return
	 */
	public static String translate(String codeType, String code) {
		if (null == codeTranslator) {
			codeTranslator = SpringContext.get().getBean(ICodeTranslator.class);
		}
		return codeTranslator.translate(codeType, code);
	}

	// 需要在MyWebMvcConfigurer中注册RequestContextListener才能获取RequestContextHolder
	private static RequestAttributes getCurrentRequestAttributes() {
		return RequestContextHolder.currentRequestAttributes();
	}

	public static HttpServletRequest getRequest() {
		return ((ServletRequestAttributes) getCurrentRequestAttributes()).getRequest();
	}

	public static HttpSession getSession() {
		return ((ServletRequestAttributes) getCurrentRequestAttributes()).getRequest().getSession();
	}

	public static HttpServletResponse getResponse() {
		return ((ServletRequestAttributes) getCurrentRequestAttributes()).getResponse();
	}

	public static Object getRequestAttribute(String name) {
		return getCurrentRequestAttributes().getAttribute(name, RequestAttributes.SCOPE_REQUEST);
	}

	public static void setRequestAttribute(String name, Object value) {
		getCurrentRequestAttributes().setAttribute(name, value, RequestAttributes.SCOPE_REQUEST);
	}

	public static Object getSessionAttribute(String name) {
		return getCurrentRequestAttributes().getAttribute(name, RequestAttributes.SCOPE_SESSION);
	}

	public static void setSessionAttribute(String name, Object value) {
		getCurrentRequestAttributes().setAttribute(name, value, RequestAttributes.SCOPE_SESSION);
	}

}
